package com.lemon.smartsafetynew.ui.activity.patrol;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerViewMultipleItemClickListener;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.common.EnterTypeEnum;
import com.lemon.smartsafetynew.entity.event.patrol.ChildItemEvent;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemConclusionVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemResultBo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemSetVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolTaskItemVo;
import com.lemon.smartsafetynew.net.services.SafePatrolServices;
import com.lemon.smartsafetynew.ui.adapter.patrol.PatrolCheckItemAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 安全巡查 ---> 巡查路线 ----> 检查项
 * Created by Andrew on 2017/8/2.
 */

public class SafePatrolCheckItemActivity extends PhotoSelectBaseActivity
        implements RecyclerViewMultipleItemClickListener<SafePatrolCheckItemVo> {


    @Bind(R.id.safe_patrol_item_name_tv)
    TextView safePatrolItemNameTv;
    @Bind(R.id.safe_patrol_item_desc_tv)
    TextView safePatrolItemDescTv;
    @Bind(R.id.patrol_ImageView)
    ImageView patrolImageView;

    @Bind(R.id.safe_patrol_item_layout)
    LinearLayout safePatrolItemLayout;

    @Bind(R.id.pass_tv)
    TextView passTv;
    @Bind(R.id.not_pass_tv)
    TextView notPassTv;
    @Bind(R.id.not_check_tv)
    TextView notCheckTv;

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    @Bind(R.id.check_item_submit_btn)
    Button checkItemSubmitBtn;

    @Bind(R.id.patrol_tv)
    TextView patrolTv;

    protected PatrolCheckItemAdapter mAdapter;

    private static SafePatrolTaskItemVo safePatrolTaskItemVo;
    private static int task_id;
    private String taskId;
    public List<SafePatrolCheckItemVo> mDataList = new ArrayList<>();
    public List<SafePatrolCheckItemResultBo> mResultList = new ArrayList<>(); // 'flow_id'+','+'conclusion_id'
    public List<Integer> mCountList = new ArrayList<>(); // 通过， 不通过， 未检查

    private SafePatrolCheckItemSetVo safePatrolCheckItemSetVo;


    @Override
    protected void getBundleArgs() {

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            safePatrolTaskItemVo = (SafePatrolTaskItemVo) bundle.get(KeyConstants.KEY_SAFE_PATROL_CHECK_ITEM_TASK);
            task_id = bundle.getInt(KeyConstants.KEY_SAFE_PATROL_TASK_ID);
            taskId = bundle.getString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW);
        }
    }

    @Override
    protected void initTitle() {
        this.setBarTitle("安全巡查");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(SafePatrolCheckItemActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_patrol_check_item;
    }

    @Override
    protected void initViews() {
        super.initViews();

        // ======= View =======
        initItemTitle();
        initRecyclerView();


        //  ====== GET NET DATA ======
        getCheckItemList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setShowAdd(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        setShowAdd(false);
    }

    private void getCheckItemList() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("item_id", safePatrolTaskItemVo.getItem_id());
        SafePatrolServices
                .init()
                .getSafePatrolCheckItemList(params);
    }

    private void initItemTitle() {

        safePatrolItemNameTv.setText(CommonUtil.avoidNullString(safePatrolTaskItemVo.getObject_title()));
        safePatrolItemDescTv.setText(CommonUtil.avoidNullString(safePatrolTaskItemVo.getLocation_code()));

//        if (safePatrolTaskItemVo.getIs_patrol() == 1) {
//            patrolTv.setVisibility(View.VISIBLE);
//            patrolImageView.setVisibility(View.VISIBLE);
//        }
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        mAdapter = new PatrolCheckItemAdapter(mDataList, this);
        recyclerView.setAdapter(mAdapter);
    }

    private void itemStatusBarView() {
        passTv.setText("通过：" + mCountList.get(0));
        notPassTv.setText("不通过：" + mCountList.get(1));
        notCheckTv.setText("待检查：" + mCountList.get(2));
    }

    private void countListStatus(List<SafePatrolCheckItemResultBo> list) {

        int pass = 0;
        int fail = 0;
        int not_check = 0;

        for (SafePatrolCheckItemResultBo checkItemResultBo : list) {

            if (checkItemResultBo.getStatus() == 1) {
                pass++;
            } else if (checkItemResultBo.getStatus() == 2) {
                fail++;
            } else {
                not_check++;
            }
        }

        //not_check = list.size() - pass - fail;

        mCountList.set(0, pass);
        mCountList.set(1, fail);
        mCountList.set(2, not_check);

        itemStatusBarView();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateRecyclerView(ChildItemEvent event) {

        int pos = event.getPosition();
        SafePatrolCheckItemResultBo resultBo = event.getResultBo();

        mResultList.set(pos, resultBo);

        countListStatus(mResultList);

        if (mAdapter != null) {
            mAdapter.setResultList(mResultList);
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(safePatrolCheckItemSetVo.getRows());
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_SAFE_PATROL_CHECK_ITEM_LIST.equals(event.getTag())) {  //获取检查子项列表
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && recyclerView != null) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    safePatrolCheckItemSetVo = (SafePatrolCheckItemSetVo) event.getObj();

                    for (SafePatrolCheckItemVo checkItemVo : safePatrolCheckItemSetVo.getRows()) { //初始化 ResultList 我们这个检查子项不点击不符合，默认是都是符合的

                        for (SafePatrolCheckItemConclusionVo checkItemConclusionVo : checkItemVo.getConclusions()) {

                            if ("green_mark".equals(checkItemConclusionVo.getMark_code())) {  //正常的检查项的检查结论必须包含"green_mark"，如果没有会造成RecyclerView Crash
                                SafePatrolCheckItemResultBo status = new SafePatrolCheckItemResultBo();
                                status.setFlow_id_conclusion_id(checkItemConclusionVo.getFlow_id() + "," + checkItemConclusionVo.getConclusion_id());
                                status.setUserChoose(false);  //我们默认选的，不是人操作的值
                                mResultList.add(status);
                                break;
                            }
                        }

                    }

                    if (safePatrolCheckItemSetVo != null
                            && safePatrolCheckItemSetVo.getRows() != null
                            && safePatrolCheckItemSetVo.getRows().size() != 0) {

                        // ==== 初始化 ====
                        mCountList.add(0);
                        mCountList.add(0);
                        mCountList.add(safePatrolCheckItemSetVo.getRows().size());

                        if (mAdapter != null) {
                            mAdapter.setResultList(mResultList);
                            mDataList.clear();
                            mAdapter.notifyDataSetChanged();
                            mAdapter.addItems(safePatrolCheckItemSetVo.getRows());
                        }

                        itemStatusBarView();
                    }

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    //TODO
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        } else if (KeyConstants.URL_SUBMIT_SAFE_PATROL_CHECK_ITEM_RESULT_NO_FILE.equals(event.getTag())) {
            /*
             * 处理提交检查项返回结果
             */
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                //mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                            //TODO
                        }
                    });

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }

        }
    }

    @OnClick({R.id.safe_patrol_item_layout, R.id.check_item_submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.safe_patrol_item_layout:
                //检查项详情
                Bundle bundle = new Bundle();
                bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_ITEM_TASK, safePatrolTaskItemVo);
                bundle.putString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW, taskId);// taskId 根据任务iD进行巡检
                UIHelper.showActivity(SafePatrolCheckItemActivity.this, bundle, SafePatrolDetailActivity.class);
                break;

            case R.id.check_item_submit_btn:
                //提交检查项结论
                doSubmitAction();

                break;
        }
    }

    /**
     * 提交检查项结论
     */
    private void doSubmitAction() {

        mHUDUtil.showHUD();

        // ============ 整合 flow_id_conclusion_id ==========
        List<String> mList = new ArrayList<>();
        for (SafePatrolCheckItemResultBo resultBo : mResultList) {
            if (!resultBo.isUserChoose()) {
                mHUDUtil.showErrorTip("请完成所有检查项的结论填写再提交巡查。");
                return;
            }
            mList.add(resultBo.getFlow_id_conclusion_id());
        }

        final LemonRequestParams params = new LemonRequestParams("");
        params.put("task_id", task_id);
        params.put("taskId",taskId);
        params.put("item_id", safePatrolTaskItemVo.getItem_id());
        params.put("check_id", safePatrolCheckItemSetVo.getCheck_id());
        params.put("flow_id_conclusion_id", mGson.toJson(mList));
        params.put("remark", "");

        SafePatrolServices
                .init()
                .submitSafePatrolItemCheckResultNoFile(params);

//        ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();
//        fixedThreadPool.execute(new Runnable() {
//            @Override
//            public void run() {
//                getUploadMediaItems(new SelectEvidenceAdapter.CropCallBack<Map<String, File>>() {
//                    @Override
//                    public void onStart() {
//
//                    }
//
//                    @Override
//                    public void onFinish(Map<String, File> data) {
//
//                        if (data == null || data.isEmpty()) {
//
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    mHUDUtil.showErrorTip("提交操作必须添加附件。");
//                                }
//                            });
//
//                        } else {
//                            SafePatrolServices
//                                    .init()
//                                    .submitSafePatrolItemCheckResult(params, data);
//                        }
//                    }
//                });
//            }
//        });

    }

    /**
     * 点击检查项
     *
     * @param data
     * @param position
     */
    @Override
    public void onItemClick(SafePatrolCheckItemVo data, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM, data);
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_BO, mResultList.get(position));
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_ENTER_TYPE, EnterTypeEnum.NOW);
        bundle.putString(KeyConstants.KEY_COMPANY_ID, safePatrolTaskItemVo.getCompany_id());
        bundle.putInt(KeyConstants.KEY_SAFE_PATROL_POSITION, position);
        bundle.putInt(KeyConstants.KEY_SAFE_PATROL_TASK_ID, task_id);
        bundle.putString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW, taskId);// taskId 根据任务iD进行巡检
        bundle.putString(KeyConstants.KEY_SAFE_PATROL_CHECK_ID, safePatrolCheckItemSetVo.getCheck_id());
        UIHelper.showActivity(this, bundle, SafePatrolCheckItemDetailActivity.class);
    }

    /**
     * 点击备注
     *
     * @param data
     * @param position
     */
    @Override
    public void onChildItemClick(SafePatrolCheckItemVo data, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM, data);
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_BO, mResultList.get(position));
        bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_ENTER_TYPE, EnterTypeEnum.NOW);
        bundle.putString(KeyConstants.KEY_COMPANY_ID, safePatrolTaskItemVo.getCompany_id());
        bundle.putInt(KeyConstants.KEY_SAFE_PATROL_POSITION, position);
        bundle.putInt(KeyConstants.KEY_SAFE_PATROL_TASK_ID, task_id);
        bundle.putString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW, taskId);
        bundle.putString(KeyConstants.KEY_SAFE_PATROL_CHECK_ID, safePatrolCheckItemSetVo.getCheck_id());
        UIHelper.showActivity(this, bundle, SafePatrolCheckItemDetailActivity.class);
    }

    /**
     * 检查子项不通过
     *
     * @param data
     * @param position
     */
    @Override
    public void onNegativeItemClick(final SafePatrolCheckItemVo data, final int position) {

        for (SafePatrolCheckItemConclusionVo safePatrolCheckItemConclusionVo : data.getConclusions()) {
            if ("red_mark".equals(safePatrolCheckItemConclusionVo.getMark_code())) { //不通过

                SafePatrolCheckItemResultBo status = new SafePatrolCheckItemResultBo();
                status.setFlow_id_conclusion_id(safePatrolCheckItemConclusionVo.getFlow_id() + "," + safePatrolCheckItemConclusionVo.getConclusion_id());
                status.setUserChoose(true);
                status.setStatus(2);

                mResultList.set(position, status);
                countListStatus(mResultList);

                break;
            }
        }

        //当检查子项不通过时，必须跳转进入检查详情页面，填写隐患处理人
        mHUDUtil.showInfoTip("跳转创建隐患页面。", new HUDUtil.CallBack() {
            @Override
            public void onCall() {
                Bundle bundle = new Bundle();
                bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM, data);
                bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_BO, mResultList.get(position));
                bundle.putSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_ENTER_TYPE, EnterTypeEnum.NOW);
                bundle.putString(KeyConstants.KEY_COMPANY_ID, safePatrolTaskItemVo.getCompany_id());
                bundle.putInt(KeyConstants.KEY_SAFE_PATROL_POSITION, position);
                bundle.putInt(KeyConstants.KEY_SAFE_PATROL_TASK_ID, task_id);
                bundle.putString(KeyConstants.KEY_SAFE_PATROL_CHECK_ID, safePatrolCheckItemSetVo.getCheck_id());
                bundle.putString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW, taskId);// taskId 根据任务iD进行巡检
                UIHelper.showActivity(SafePatrolCheckItemActivity.this, bundle, SafePatrolCheckItemDetailActivity.class);
            }
        });

    }

    /**
     * 检查子项通过
     *
     * @param data
     * @param position
     */
    @Override
    public void onPositiveItemClick(SafePatrolCheckItemVo data, int position) {

        for (SafePatrolCheckItemConclusionVo safePatrolCheckItemConclusionVo : data.getConclusions()) {
            if ("green_mark".equals(safePatrolCheckItemConclusionVo.getMark_code())) { //通过

                SafePatrolCheckItemResultBo status = new SafePatrolCheckItemResultBo();
                status.setFlow_id_conclusion_id(safePatrolCheckItemConclusionVo.getFlow_id() + "," + safePatrolCheckItemConclusionVo.getConclusion_id());
                status.setUserChoose(true);
                status.setStatus(1);

                mResultList.set(position, status);
                countListStatus(mResultList);

                break;
            }
        }

    }

}
